var cutPage_num = 1; //当前页数
var subTotal = 0; //总页数
var delPage = false;//是否需要删除一页
/*表格渲染*/
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
function orderList(data) {
    dataSource.splice(0, dataSource.length);//清空数组
    $.each(data.tradeBoxList, function (i, field) {
        var rowData = new Array();
        rowData.push(field.customerName);
        rowData.push(field.customerLoginAccount);
        rowData.push(field.updateTime);
        rowData.push(field.createUserName);
        rowData.push(field.purchaseCount);
        rowData.push(field.totalMoney);
        rowData.push("编辑");
        rowData.push(field.boxId);
        rowData.push(field.provinceCode);
        rowData.push(field.createUserId);
        rowData.push(field.customerId);
        rowData.push(field.memberId);
        rowData.push(field.cityCode);
        rowData.push(field.warehouseId);
        // rowData.push(field.received_phone);
        // rowData.push(field.source);
        dataSource.push(rowData);
    });
    initDataTable(dataSource);
    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "order": [[ 2, "desc" ]],
            "autoWidth": false,
            "ordering": true,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [5, 10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data,type,row,meta){
                        var val = Number(row[5]).toFixed(2);
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function(data,type,row,meta){
                        var quzhi=JSON.parse(web.readCookie("loginData")).user.name;
                        if(row[3]==quzhi){
                            var val = '<span style="margin-right: 10px;" class="powerButton 98">' +
                                '<a onclick="goNextPage(\''+row[7]+'\',\''+row[8]+'\',\''+row[9]+'\',\''+row[10]+'\',\''+row[11]+'\',\''+row[12]+'\',\''+row[13]+'\')">编辑</a></span><span><a onclick="deletSelect('+row[9]+','+row[7]+',this)">删除</a></span>';
                            return val;
                        }else{
                            var val = '<span class="powerButton 98"><a onclick="goNextPage(\''+row[7]+'\',\''+row[8]+'\',\''+row[9]+'\',\''+row[10]+'\',\''+row[11]+'\',\''+row[12]+'\',\''+row[13]+'\')">编辑</a></span>';
                            return val;
                        }
                    },
                    "targets": 6
                },
            ]
        });
        //权限控制函数
        power()
    };
}
function getList(page_num){
    $("#area").val()
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.replaceInter.replace_searchBox,
        cache: false,  //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            customerLoginAccount:$("#customerLoginAccount").val(),
            customerName:$("#customerName").val(),
            createTimeBegin:$("#timemin").val(),
            createTimeEnd:$("#timemax").val(),
            createUserName:$("#createUserName").val(),
            pageNum: page_num, //当前页码
            pageSize: 20,//每页显示条数
        }),
        success: function (result) {
            if(result.errorCode=="0"){
                orderList(result);
                if(result.total%20==0){
                    subTotal=parseInt(result.total/20);
                }else if(result.total%20==1){
                    delPage = true;
                    subTotal=parseInt(result.total/20)+1;
                }else {
                    subTotal=parseInt(result.total/20)+1;
                }
                $('.M-box3').pagination({
                    pageCount: subTotal, //总页数
                    jump: true,
                    coping: true,
                    prevContent: '上页',
                    nextContent: '下页',
                    callback: function (api) {
                        cutPage_num = api.getCurrent();
                        $.ajax({
                            contentType: "application/json",
                            type: "POST",
                            url:root.replaceInter.replace_searchBox,
                            cache: false,  //禁用缓存
                            dataType: "json",
                            data: JSON.stringify({
                                customerLoginAccount:$("#customerLoginAccount").val(),
                                customerName:$("#customerName").val(),
                                createTimeBegin:$("#timemin").val(),
                                createTimeEnd:$("#timemax").val(),
                                createUserName:$("#createUserName").val(),
                                pageNum: api.getCurrent(), //当前页码
                                pageSize: 20,//每页显示条数
                            }),
                            success: function (result) {
                                if(result.errorCode=="0"){
                                    orderList(result);
                                }else {
                                    layer.msg(result.errorMessage, {icon: 5,time:1000});
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                alert(XMLHttpRequest);
                            }
                        });
                    }
                });
            }else {
                layer.msg(result.errorMessage, {icon: 5,time:1000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
/*删除草稿*/
var meshis=""
var delBoxId = "";
var delCreateUserId = "";
function deletSelect(createUserId,boxId,methis) {
    meshis=methis
    delBoxId = boxId;
    delCreateUserId = createUserId;
    $("#modal-delete").modal("show");
}
/*确定删除草稿*/
function deleteSelectSure(){
    var quzhi=JSON.parse(web.readCookie("loginData")).user.user_ID
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url:root.replaceInter.replace_deleteBoxByOperator,
        cache: false,  //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            createUserId:delCreateUserId,
            boxId:delBoxId
        }),
        success: function (data) {
            if(data.errorCode=="0"){
                // $(meshis).parent().parent().parent().remove();
                if(delPage&&cutPage_num==subTotal){
                    getList(cutPage_num-1);
                }else {
                    getList(cutPage_num)
                }
                layer.msg('删除成功', {icon: 6,time:1000});
                $("#modal-delete").modal("hide");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
// 编辑
function goNextPage(boxId,provinceId,createUserId,customerId,memberId,cityCode,warehouseId) {
    console.log(cityCode)
    var draftsObj = {
        boxId:boxId,
        provinceId:provinceId,
        createUserId:createUserId,
        customerId:customerId,
        memberId:memberId,
        cityCode:cityCode,
        warehouseId:warehouseId
    }
    sessionStorage.setItem("draftObj",JSON.stringify(draftsObj));
    $(window.parent.document).find("#replaceOrder")[0].click();
}